package yunjiao.javatutorials.guava.base.functional;

import com.google.common.base.Equivalence;
import com.google.common.base.Function;


/**
 * 常用方法
 *
 * @author yangyunjiao
 */
public class FunctionalEquivalenceDemo {
    record Person(String name, int age) {

        @Override
        public String toString() {
            return String.format("Person{name='%s', age=%d}", name, age);
        }
    }

    public static void main(String[] args) {
        // 基于名称的等价关系
        Function<Person, String> nameFunction = Person::name;
        Equivalence<Person> nameEquivalence =
                Equivalence.equals().onResultOf(nameFunction);

        Person person1 = new Person("Alice", 25);
        Person person2 = new Person("Alice", 30);
        Person person3 = new Person("Bob", 25);

        System.out.println("基于名称比较:");
        System.out.println("person1 ≈ person2: " + nameEquivalence.equivalent(person1, person2));
        System.out.println("person1 ≈ person3: " + nameEquivalence.equivalent(person1, person3));

        // 基于年龄的等价关系
        Function<Person, Integer> ageFunction = Person::age;
        Equivalence<Person> ageEquivalence =
                Equivalence.equals().onResultOf(ageFunction);

        System.out.println("\n基于年龄比较:");
        System.out.println("person1 ≈ person2: " + ageEquivalence.equivalent(person1, person2));
        System.out.println("person1 ≈ person3: " + ageEquivalence.equivalent(person1, person3));
    }
}
